import { defineStore } from 'pinia'
import { setStore, getStore, showModal } from '@/utils'
import { STORAGE_KEYS } from '@/common/constants/index'
import { loginApi, checkAppletMemberExistApi, getUserInfoByTokenApi, getBuildingDetailApi, logoutApi } from '@/common/api/base'
import { getNoticeList } from '@/common/api/common'
import { formatRoom } from '@/common/format'
type StateType = {
  token: string | any
  userInfo: any
  currentRoom: any
  needGetPhone: boolean
  notificationList: any[]
}
type GetterType = {
  roomInfo: (state: StateType) => string
}

type ActionType = {
  setToken: (token: string) => void
  setUserInfo: (userInfo: any) => void
  loginAction: (params: any) => Promise<any>
  checkNeedGetPhone: () => Promise<boolean>
  getUserInfoByToken: () => Promise<any>
  getNotification: (communityId: number) => Promise<any>
  logout: () => void
}

export const useAccountStore = defineStore<string, StateType, GetterType, ActionType>('accountStore', {
  state: () => {
    return {
      token: getStore(STORAGE_KEYS.TOKEN) || '',
      userInfo: getStore(STORAGE_KEYS.USERINFO) || {},
      currentRoom: {},
      needGetPhone: true,
      notificationList: []
    }
  },
  getters: {
    roomInfo: state => {
      return formatRoom(state.currentRoom)
    }
  },
  actions: {
    setToken(token) {
      this.token = token
      setStore(STORAGE_KEYS.TOKEN, token)
    },
    setUserInfo(userInfo) {
      this.userInfo = userInfo || {}
      setStore(STORAGE_KEYS.USERINFO, userInfo)
    },
    async loginAction(params: any) {
      return new Promise((resolve, reject) => {
        uni.showLoading({
          title: '登陆中...'
        })
        wx.login({
          success: async (res: { code: string }) => {
            const { code } = res
            loginApi({ ...params, code })
              .then((data: any) => {
                console.log('获取token', data)
                this.setToken(data || '')
                this.getUserInfoByToken()
                resolve(data!)
              })
              .catch((err: any) => {
                reject(err)
              })
          },
          complete: () => {
            uni.hideLoading()
          },
          fail: (err: any) => {
            reject(err)
          }
        })
      })
    },
    async checkNeedGetPhone() {
      return new Promise((resolve, reject) => {
        uni.login({
          success: (res: { code: string }) => {
            console.log('[ checkNeedGetPhone ] >', res)
            checkAppletMemberExistApi(res.code).then((res: any) => {
              // 返回true表示已经注册， 不需要获取手机号
              this.needGetPhone = !res
              uni.switchTab({
                url: '/pages/home/index'
              })
              resolve(!res)
            })
          },
          fail: (err: any) => {
            reject(err)
          }
        })
      })
    },
    // 根据token获取用户信息
    async getUserInfoByToken() {
      return getUserInfoByTokenApi().then(async (res: any) => {
        if (res.roomId) {
          const detail: any = await getBuildingDetailApi({ roomId: res.roomId })
          if (detail && detail.roomId) {
            this.currentRoom = {
              ...detail,
              statusText: detail.status === 2 ? '审核通过' : '待审核'
            }
            this.getNotification(detail.communityId)
          } else {
            this.currentRoom = {}
          }
        } else {
          this.currentRoom = {}
        }
        this.setUserInfo(res || {})
        return res
      })
    },
    async getNotification(communityId: number) {
      getNoticeList({ pageNo: 1, pageSize: 9999, communityId }).then((res: any) => {
        this.notificationList = res.records || []
      })
    },
    async logout() {
      showModal({
        title: '提示',
        content: '确定退出登录吗？',
        success: () => {
          logoutApi().then(() => {
            uni.clearStorage()
            this.setToken('')
            this.setUserInfo({})
            this.currentRoom = {}
            this.notificationList = []
            this.needGetPhone = true
          })
        },
        cancel: () => {}
      })
    }
  }
})

export const useAccountStoreWith = () => {
  return useAccountStore()
}
